<template>
  <div class="app-container calendar-list-container">
    <div class="apply-query">
      <el-row class="filter-query">
        <el-col><span>{{ $t('customer.queryCondition') }}</span></el-col>
      </el-row>
      <el-form :inline="true" style="padding: 0 20px">
        <el-row style="padding-bottom: 10px">
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{ $t('customer.customerId') }}</div>
              <el-input @keyup.enter.native="handleFilter" class="filter-item" v-model="listQuery.customerNo" clearable :placeholder="$t('placeholder.content')"></el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{ $t('customer.customerName') }}</div>
              <el-input @keyup.enter.native="handleFilter" class="filter-item" v-model="listQuery.customerName" clearable :placeholder="$t('placeholder.content')"></el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{ $t('customer.customerShortName') }}</div>
              <el-input @keyup.enter.native="handleFilter" class="filter-item" v-model="listQuery.customerShortName" clearable :placeholder="$t('placeholder.content')"></el-input>
            </div>
          </el-col>
          <el-col :span="4" style="margin-top: 33px">
            <el-button class="yt-btn-ys" type="primary" icon="search" @click="handleFilter">{{ $t("button.search") }}</el-button>
            <el-button class="yt-btn" type="primary" @click="reset">{{$t("button.reset")}}</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="data-list">
      <div class="list-content">
        <span>{{ $t("customer.customerList") }}</span>
      </div>
      <div class="list-operation">
        <!--新增-->
        <el-button class="yt-btn-ys" type="primary" @click="addCustomerDialogVisible = true">{{ $t("button.new") }}</el-button>
        <el-button class="yt-btn" @click="handleDelete">{{ $t("button.delete") }}</el-button>
        <el-button class="yt-btn" @click="handlePreserve">{{$t("button.update")}}</el-button>
      </div>
      <el-table :key="tableKey" :data="list" :empty-text="$t('placeholder.emptyText')" border v-loading.body="listLoading" fit highlight-current-row @selection-change="handleSelectionChanges" class="yt-table yt-temporary" max-height="600">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column align="center" type="index" :label="$t('customer.serialNum')" width="50"/>
        <el-table-column align="center" :label="$t('customer.customerId')" prop="customerNo" class-name="bg"/>
        <el-table-column align="center" :label="$t('customer.customerName')" width="180">
          <template slot-scope="scope">
            <el-input size="small" v-model="scope.row.customerName" :disabled="scope.row.dataFrom !== 'OMS'"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('customer.customerShortName')" width="180">
          <template slot-scope="scope">
            <el-input size="small" v-model="scope.row.customerShortName" :disabled="scope.row.dataFrom !== 'OMS'"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" :label="$t('customer.dataFrom')" prop="dataFrom" class-name="bg"/>
        <el-table-column align="center" prop="createTime" :label="$t('customer.createTime')" class-name="bg"/>
        <el-table-column align="center" prop="createName" :label="$t('customer.createName')" class-name="bg"/>
        <el-table-column align="center" prop="updateTime" :label="$t('customer.updateTime')" class-name="bg"/>
        <el-table-column align="center" prop="updateName" :label="$t('customer.updateName')" class-name="bg"/>
      </el-table>
      <div v-show="!listLoading" class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="listQuery.page"
          :page-sizes="[10, 20, 30, 50, 100, 200]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>


    <el-dialog
      :title="$t('customer.addCustomer')"
      :visible.sync="addCustomerDialogVisible"
      :before-close="addCustomerDialogVisibleClose"
    >
      <el-form ref="form" :model="customerInfo" label-width="80px">
        <!--<el-form-item :label="$t('customer.customerId')">
          <el-input v-model="customerInfo.customerNo"></el-input>
        </el-form-item>-->
        <el-form-item :label="$t('customer.customerName')">
          <el-input v-model="customerInfo.customerName"></el-input>
        </el-form-item>
        <el-form-item :label="$t('customer.customerShortName')">
          <el-input v-model="customerInfo.customerShortName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCustomerDialogVisible = false">{{
          $t("button.cancel")
        }}</el-button>
        <el-button type="primary" @click="addCustomer">{{
          $t("button.determine")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import customerReq from '@/api/customer';
  import formatter from '@/utils/formatter';
  import { mapGetters } from 'vuex';

  export default {
    name: 'customerManage',
    data() {
      return {
        customerReq,
        formatter,
        addCustomerDialogVisible: false,
        form: {
          customerNo: undefined,
          customerName: undefined,
          customerShortName: undefined
        },
        customerInfo: {
          customerNo: undefined,
          customerName: undefined,
          customerShortName: undefined,
          dataFrom: 'OMS'
        },
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          customerNo: '',
          customerName: '',
          customerShortName: ''
        },
        userManager_btn_edit: false,
        userManager_btn_del: false,
        userManager_btn_add: false,
        textMap: {
          update: '编辑',
          create: '创建'
        },
        tableKey: 0,
        selectionList: []
      };
    },
    created() {
      this.getQuery();
      this.getList();
      this.userManager_btn_edit = this.elements['userManager:btn_edit'];
      this.userManager_btn_del = this.elements['userManager:btn_del'];
      this.userManager_btn_add = this.elements['userManager:btn_add'];
    },
    activated() {
      this.getQuery();
    },
    computed: {
      ...mapGetters(['elements'])
    },
    methods: {
      getQuery() {
        const searchCustomerQuery = window.sessionStorage.getItem('searchCustomerQuery');
        if (searchCustomerQuery) {
          this.listQuery = JSON.parse(searchCustomerQuery);
        }
      },
      getList() {
        this.listLoading = true;
        customerReq.page(this.listQuery).then(response => {
          this.list = response.data.rows;
          this.total = response.data.total;
          this.listLoading = false;
          for (const customer of this.list) {
            if (customer.createTime) {
              customer.createTime = this.formatter.formatTimes(
                '',
                '',
                customer.createTime
              );
            }
            if (customer.updateTime) {
              customer.updateTime = this.formatter.formatTimes(
                '',
                '',
                customer.updateTime
              );
            }
          }
        });
      },
      handleFilter() {
        this.getList();
      },
      reset() {
        this.listQuery = {};
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },
      resetTemp() {
        this.form = {
          customerNo: undefined,
          customerName: undefined,
          customerShortName: undefined
        };
      },
      addCustomerDialogVisibleClose() {
        this.customerInfo = {
          customerNo: undefined,
          customerName: undefined,
          customerShortName: undefined,
          dataFrom: 'OMS'
        };
        this.addCustomerDialogVisible = false;
      },
      addCustomer() {
        if (
          this.customerInfo.customerName === '' ||
          this.customerInfo.customerName === undefined
        ) {
          this.$message({
            message: this.$t('customer.enterCustomerName'), // 请输入客户名称
            type: 'error'
          });
          return false;
        }
        if (
          this.customerInfo.customerShortName === '' ||
          this.customerInfo.customerShortName === undefined
        ) {
          this.$message({
            message: this.$t('customer.enterCustomerShortName'),
            type: 'error'
          });
          return false;
        }
        customerReq.addObj(this.customerInfo).then(res => {
          this.$notify({
            title: res.status === 200 ? this.$t('tips.success') : this.$t('tips.fail'),
            message: res.status === 200 ? this.$t('tips.success') : res.message,
            type: res.status === 200 ? 'success' : 'warning'
          });
          this.addCustomerDialogVisible = false;
          this.reset();
        });
      },
      beforeDestroy() {
        window.sessionStorage.setItem(
          'searchCustomerQuery',
          JSON.stringify(this.listQuery)
        );
      },
      handleDelete() {
        if (this.selectionList.length <= 0) {
          this.$notify({
            title: this.$t('tips.fail'),
            message: this.$t('placeholder.content'),
            type: 'warning'
          });
          return;
        }
        this.$confirm(this.$t('tips.permanentDelete'), this.$t('tips.tips'), {
          confirmButtonText: this.$t('tips.determine'),
          cancelButtonText: this.$t('tips.cancel'),
          type: 'warning'
        }).then(() => {
          // this.selectionList.forEach((item, index) => {
          //   if (item.vendorType && item.vendorType.length > 0) {
          //     const vendorType = item.vendorType.join(',')
          //     this.selectionList[index].vendorType = vendorType
          //   } else {
          //     this.selectionList[index].vendorType = ''
          //   }
          // })
          const list = [];
          for (const i of this.selectionList) {
            list.push(i.id);
          }
          // console.log(list,'ddfdfadfafsadfsadf')
          customerReq.deleteList(list).then(() => {
            this.$notify({
              title: this.$t('tips.success'),
              message: this.$t('tips.deleteSuccess'),
              type: 'success',
              duration: 2000
            });
            this.getList();
          });
        });
      },
      handleSelectionChanges(val) {
        this.selectionList = val;
        // JSON.stringify()
        // console.log(this.selectionList, 'dddddddddddddddd')
      },
      handlePreserve() {
        // 修改保存函数
        if (this.selectionList.length <= 0) {
          this.$notify({
            title: this.$t('tips.fail'),
            message: this.$t('placeholder.content'),
            type: 'warning'
          });
          return;
        }
        this.selectionList.forEach(x => {
          if (x.createTime) {
            delete x.createTime
          }
          if (x.updateTime) {
            delete x.updateTime
          }
        })
        customerReq.batchSave(this.selectionList).then(res => {
          this.listLoading = false;
          this.$notify({
            title: res.status === 200 ? this.$t('tips.success') : this.$t('tips.fail'),
            message: res.data || res.message,
            type: res.status === 200 ? 'success' : 'warning'
          });
          this.getList();
        });
      }
    }
  };
</script>
